<?php
/**
 * 健保项目接口
 */

namespace App\Http\Controllers\Api;

use App\Models\LogHelper;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Services\IdEncryptService;
use CategoryRepository;
use TestingConfig;
use TestingDetailService;
use TestingDeveloperService;
use UserRecordService;
use TestingUserEnterpriseRelFacadeService;
use ResultTypeService;

class TbController extends Controller
{
    /**
     * 太保的授权接口
     */


    public function auth(Request $request)
    {
        try {
            $appid = $request->input('appid');
            if (!$appid) {
                return apiErrcode('appid_invalid');
            }
            $appsecret = $request->input('appsecret');
            if (!$appsecret) {
                return apiErrcode('appsecret_invalid');
            }
            $timestamp = $request->input('timestamp');
            if (!$appsecret) {
                return apiErrcode('timestamp_invalid');
            }
            $signature = $request->input('signature');
            if (!$appsecret) {
                return apiErrcode('sign_invalid');
            }
            $params = [];
            array_push($params, $appid);
            array_push($params, $appsecret);
            array_push($params, $timestamp);
            sort($params);
            $signStr = implode("", $params);
            $mdStr = md5($signStr);
            if ($signature != $mdStr) {
                return apiErrcode('sign_invalid');
            }
            $targetDeveloper = TestingDeveloperService::getByAppid($appid, $appsecret);

            if (!$targetDeveloper) {
                return apiErrcode('appid_invalid');
            }
            $union_code = $targetDeveloper['union_code'];
            //全部校验通过之后，根据查询出来的 unioncode查询 testing_detail表中的符合条件的题目列表
            //根据查询的结果返回列表数据
            $testingList = TestingDetailService::getByUnionCode($union_code);

            $datas = [];
            if (count($testingList) > 0) {

                $url = TestingConfig::getValue('TB.test.list');
                foreach ($testingList as $key => $val) {
                    $tid = IdEncryptService::encryption($val['id'], 'encode');
                    $obj['tid'] = $tid;
                    $obj['name'] = $val['name'];
                    $obj['url'] = $url . $tid;
                    array_push($datas, $obj);
                }
            }
            return apiSuccess($datas);
        } catch (Exception $e) {
            return apiFailed();
        }
    }

    public function result($originTid, $uid, $enterpriseId)
    {
        try {

            $url = TestingConfig::getValue('TB.test.content',null,true);

            if(!$originTid){
                return apiErrcode('tid_invalid');
            }
            if(!$uid ){
                return apiErrcode('uid_invalid');
            }
            if(!$enterpriseId){
                return apiErrcode('enterprise_id_invalid');
            }

            //此部分是为了做数据的校验。确保数据是正确的

            $tid = IdEncryptService::encryption($originTid, 'decode');

            $tid = $tid[0];
            if(!$testingInfo = TestingDetailService::getById($tid)){
                return apiErrcode('tid_invalid');
            }
            $result = TestingUserEnterpriseRelFacadeService::getByUidEid($uid, $enterpriseId);

            /**开发着的名称*/
            $developer = TestingDeveloperService::getByUnionCode($testingInfo['dev_union_code']);
            //别称
            $thirdPartyName = $developer['abbreviation'];
            //最最终要跳转的测评地址
            $requestUrl = $url.$originTid.'/'.$uid.'?thirdpartyName='.$thirdPartyName;
            $log = [
                'uid' => $uid,
                'tid' => $tid,
                'thirdPartyName' => $thirdPartyName,
                'requestUrl' => $requestUrl,
            ];
//            LogHelper::log($log,'thirdpartyAccessLog');
            if (count($result)<=0) {
                $developerInfo = TestingDetailService::selectDevUnionCodeByTid($tid);
                $data['user_id'] = $uid;
                $data['enterprice_id'] = $enterpriseId;
                $data['union_code'] = $developerInfo['dev_union_code'];
                TestingUserEnterpriseRelFacadeService::store($data);

            }
            redirectToUrl($requestUrl);
        } catch (Exception $e) {
            return apiFailed();
        }
    }


    /*{"appid":"qz12377e8273c001f7","appsecret":"d413961dd74c7aed9ec3f6f091ed81fc7c890c9","timestamp":"1483495099","signature":"71b008c4bfc624a32e48b9362ffaecd8"}*/
    /**
     * 太保的根据tid统计人数接口
     */
    public function countPerson($tid, $appid, $enterpriseId)
    {
        try {
            if(!$tid){
                return apiErrcode('tid_invalid');
            }
            if (!$appid) {
                return apiErrcode('appid_invalid');
            }
            if(!$enterpriseId){
                return apiErrcode('enterprise_id_invalid');
            }
            $tid = IdEncryptService::encryption($tid, 'decode');
            //做数据安全校验
            if(!$testingInfo = TestingDetailService::getById($tid[0])){
                return apiErrcode('tid_invalid');
            }
            $count = UserRecordService::getCountByTidEid($tid, $enterpriseId);
            $count = $count ? $count : 0;
            return apiSuccess($count);

        } catch (Exception $e) {
            return apiFailed();
        }

    }

    /**
     * 太保的数据分析接口，此接口做备用，一次性返回所有的测评的人数以及结果
     */
    public function alynasis()
    {

    }




}
